package struct.exercise.write;

import java.util.Arrays;
import java.util.NoSuchElementException;

public class MyArrayList<E> {
    /**
     * addLast
     * add
     * addFirst
     * removeLast
     * remove
     * removeFirst
     * get
     * set
     */
    private E[] data;
    private int size;

    private static final int INITIAL_SIZE = 1;

    public MyArrayList(){
        this(INITIAL_SIZE);
    }

    public MyArrayList(int initialSize) {
        data = (E[] )new Object[initialSize];
        size =0;
    }

    public void addLast(E e){
        int cap = data.length;
        if(cap == size){
            resize(2*size);
        }
        data[size] = e;
        size++;
    }

    public void add(int index,E e){
        if(checkIndexOutOfBound(index)){
            throw new ArrayIndexOutOfBoundsException("数组越界");
        }
        int cap = data.length;
        if(cap == size){
            resize(2*size);
        }
        for (int i = size-1; i <=index ; i--) {
            data[i+1] = data[i];
        }
        data[index] = e;
        size++;
    }

    public void addFirst(E e){
        add(0,e);
    }

    public E removeLast() {
        if(size==0){
            throw new NoSuchElementException();
        }
        int cap = data.length;
        if(size == cap/4){
            resize(cap / 2);
        }
        E deletedVal = data[size - 1];
        // 删除最后一个元素
        // 必须给最后一个元素置为 null，否则会内存泄漏
        data[size - 1] = null;
        size--;
        return deletedVal;
    }
    private boolean checkIndexOutOfBound(int index) {
        return index >=0 &&  index <=size;
    }

    private void resize(int length) {
        E[] newArr = (E[]) new Object[length];
        for (int i = 0; i < data.length; i++) {
            newArr[i] = data[i];
        }
        data = newArr;
    }



    private void display() {
        System.out.println("size = " + size + " cap = " + data.length);
        System.out.println(Arrays.toString(data));
    }


    public static void main(String[] args) {
//        // 初始容量设置为 3
//        MyArrayList<Integer> arr = new MyArrayList<>(3);
//
//        // 添加 5 个元素
//        for (int i = 1; i <= 5; i++) {
//            arr.addLast(i);
//        }
//
//        arr.remove(3);
//        arr.add(1, 9);
//        arr.addFirst(100);
//        int val = arr.removeLast();
//
//        for (int i = 0; i < arr.size(); i++) {
//            System.out.println(arr.get(i));
//        }
    }

}
